package zxs.sino.elite.hub.service.impl;

import com.google.code.kaptcha.Producer;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import zxs.sino.elite.hub.constant.RoleConstant;
import zxs.sino.elite.hub.exception.BizCodeEnums;
import zxs.sino.elite.hub.exception.RRException;
import zxs.sino.elite.hub.mapper.sys.SysUserMapper;
import zxs.sino.elite.hub.model.form.LoginForm;
import zxs.sino.elite.hub.model.model.UserModel;
import zxs.sino.elite.hub.model.sys.SysUserEntity;
import zxs.sino.elite.hub.utils.PasswordEncoderUtil;
import zxs.sino.elite.hub.service.AdminAuthService;
import zxs.sino.elite.hub.utils.RedisKeys;
import zxs.sino.elite.hub.utils.RedisUtil;
import zxs.sino.elite.hub.utils.JwtUtil;
import zxs.sino.elite.hub.utils.UserContext;

import java.awt.image.BufferedImage;

/**
 * @author zhang
 */
@Service("adminAuthService")
@RequiredArgsConstructor
public class AdminAuthServiceImpl implements AdminAuthService {

    private final Producer producer;

    private final JwtUtil securityUtils;

    private final RedisUtil redisUtil;

    private final SysUserMapper sysUserMapper;

    private final PasswordEncoderUtil passwordEncoderUtil;


    /**
     * 获取图片验证码
     *
     * @param uuid
     * @return
     */
    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();
        redisUtil.set(RedisKeys.getLoginCodeKey(RoleConstant.ADMIN, uuid), code, 5 * 60);

        return producer.createImage(code);
    }

    /**
     * 管理员登录
     *
     * @param loginForm
     * @return
     */
    @Override
    public String login(LoginForm loginForm) {
        // 1.校验验证码
        String code = (String) redisUtil.get(RedisKeys.getLoginCodeKey(RoleConstant.ADMIN, loginForm.getUuid()));
        // redis中验证码失效
        if (code == null) {
            throw new RRException(BizCodeEnums.CODE_EXPIRED_EXCEPTION.getMsg());
        }

        // 验证码校验失败
        if (!loginForm.getCode().equals(code)) {
            throw new RRException(BizCodeEnums.CODE_ERROR_EXCEPTION.getMsg());
        }

        // 2.获取用户信息
        SysUserEntity user = sysUserMapper.queryByUserName(loginForm.getAuthKey());
        //账号不存在、密码错误
        if(user  ==  null || !passwordEncoderUtil.matches(loginForm.getAuthPassword(), user.getPassword())) {
            throw new RRException(BizCodeEnums.LOGIN_PASSWORD_EXCEPTION.getMsg());
        }

        //账号锁定
        if(user.getStatus()  ==  0){
            throw new RRException(BizCodeEnums.ACCOUNT_LOCKED_EXCEPTION.getMsg());
        }

        // 3.用户存在生成Jwt令牌
        String token = securityUtils.generateToken(new UserModel(user.getUserId(), loginForm.getAuthKey(), RoleConstant.ADMIN));

        // 4.将Jwt令牌存储到redis中，并设置过期时间为1天
        redisUtil.set(RedisKeys.getRoleKey(RoleConstant.ADMIN, loginForm.getAuthKey()), token, 24 * 60 * 60);

        return token;
    }

    /**
     * 用户退出
     */
    @Override
    public void logout() {
        UserModel userInfo = UserContext.getUserInfo();
        redisUtil.delete(RedisKeys.getRoleKey(userInfo.getRole(), userInfo.getAuthKey()));
        // 清除用户上下文
        UserContext.clear();
    }
}